package com.zggk.iroad.diease.dieaseadd;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.lxj.matisse.Matisse;
import com.zggk.iroad.R;
import com.zggk.iroad.api.MyAppliCation;
import com.zggk.iroad.db.BhLxInfo;

import com.zggk.iroad.db.DieaseInfo;
import com.zggk.iroad.db.EntityManager;

import com.zggk.iroad.greendao.BhInfoDao;
import com.zggk.iroad.greendao.BhLxInfoDao;


import com.zggk.iroad.greendao.DieaseInfoDao;
import com.zggk.iroad.greendao.LxInfoDao;
import com.zggk.iroad.mvp.MVPBaseActivity;
import com.zggk.iroad.util.MyUtils;
import com.zggk.iroad.util.NoScroolGridView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class DieaseAddActivity extends MVPBaseActivity<DieaseAddContract.View, DieaseAddPresenter> implements DieaseAddContract.View {

    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.cancle_button)
    TextView cancleButton;
    @Bind(R.id.xcry_te)
    TextView xcryTe;
    @Bind(R.id.xcry_lay)
    LinearLayout xcryLay;
    @Bind(R.id.lx_te)
    TextView lxTe;
    @Bind(R.id.lx_lay)
    LinearLayout lxLay;
    @Bind(R.id.xcsj_te)
    TextView xcsjTe;
    @Bind(R.id.xcsj_lay)
    LinearLayout xcsjLay;
    @Bind(R.id.szh_k)
    TextView szhK;
    @Bind(R.id.szh_km)
    EditText szhKm;
    @Bind(R.id.szh_bm)
    EditText szhBm;
    @Bind(R.id.szh_lay)
    LinearLayout szhLay;
    @Bind(R.id.tzh_k)
    TextView tzhK;
    @Bind(R.id.tzh_km)
    EditText tzhKm;
    @Bind(R.id.tzh_bm)
    EditText tzhBm;
    @Bind(R.id.tzh_lay)
    LinearLayout tzhLay;
    @Bind(R.id.xsfx_lay)
    LinearLayout xsfxLay;
    @Bind(R.id.bhlx_te)
    TextView bhlxTe;
    @Bind(R.id.bhlx_lay)
    LinearLayout bhlxLay;
    @Bind(R.id.bhmc_te)
    TextView bhmcTe;
    @Bind(R.id.bhmc_lay)
    LinearLayout bhmcLay;
    @Bind(R.id.bhsl_te)
    EditText bhslTe;
    @Bind(R.id.bhsl_lay)
    LinearLayout bhslLay;
    @Bind(R.id.bz_lay)
    LinearLayout bzLay;
    @Bind(R.id.bz_et)
    EditText bzEt;
    @Bind(R.id.tjtp_lay)
    LinearLayout tjtpLay;
    @Bind(R.id.add_pic_grid)
    NoScroolGridView addPicGrid;
    @Bind(R.id.add_pic_lay)
    LinearLayout addPicLay;
    @Bind(R.id.save_te)
    TextView saveTe;
    @Bind(R.id.add_te)
    TextView addTe;
    @Bind(R.id.add_lay)
    LinearLayout addLay;
    @Bind(R.id.disease_shang_txt)
    TextView diseaseShangTxt;
    @Bind(R.id.disease_xia_txt)
    TextView diseaseXiaTxt;
    @Bind(R.id.disease_quan_txt)
    TextView diseaseQuanTxt;

    private DieaseInfoDao dieaseInfoDao;
    private String LXMC = "";
    private String LXID = "";
    private DieaseAddGird dieaseAddGird;
    private Map<Integer, DieaseAddGird> mapAdapter = new HashMap<>();
    private int REQUEST_CODE_CHOOSE = 66;
    private int childViewPosition;//点击拍照获取的childveiw下标
    private OptionsPickerView pickerView;

    private int SelInt = 1;
    private LxInfoDao lxInfoDao;
    private BhInfoDao bhInfoDao;
    private Long ID;
    private BhLxInfoDao bhLxInfoDao;
    private String BHLXMC;
    private String BHMCID;
    private String BHMCMC;

    public void setChildViewPosition(int childViewPosition) {
        this.childViewPosition = childViewPosition;
    }

    @Override
    public void onRequestError(String msg) {

    }

    @Override
    protected int getLayout() {
        return R.layout.act_diease_add;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        initData();
        initView();
    }

    private void initData() {
        bhLxInfoDao = EntityManager.getInstance().getBhLxInfoDao();
        bhInfoDao = EntityManager.getInstance().getBhInfoDao();
        lxInfoDao = EntityManager.getInstance().getLxInfoDao();
        dieaseInfoDao = EntityManager.getInstance().getDieaseInfoDao();
    }

    private void initView() {
        titleText.setText("病害采集");
        xcryTe.setText(MyAppliCation.spUtils.getString("OrgName"));
        LXMC = lxInfoDao.loadAll().get(0).getLXMC();
        LXID = lxInfoDao.loadAll().get(0).getLXID();
        lxTe.setText(lxInfoDao.loadAll().get(0).getLXMC());
        ArrayList<Drawable> listPicture = new ArrayList<>();
        ArrayList<String> listImgUrl = new ArrayList<>();
        Drawable addPicture = getResources().getDrawable(R.drawable.img_add_pic);
        listPicture.add(addPicture);
        final int childPosition = addPicLay.getChildCount();
        dieaseAddGird = new DieaseAddGird(this, listPicture, listImgUrl, childPosition);
        addPicGrid.setAdapter(dieaseAddGird);
        mapAdapter.put(childPosition, dieaseAddGird);
    }

    @OnClick({R.id.back, R.id.lx_lay, R.id.xcsj_lay, R.id.bhlx_lay, R.id.bhmc_lay,
            R.id.disease_shang_txt, R.id.disease_xia_txt, R.id.disease_quan_txt,
            R.id.save_te, R.id.add_te})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.lx_lay:
                List<String> LxDatas = new ArrayList<>();
                LxDatas.clear();
                for (int i = 0; i < lxInfoDao.loadAll().size(); i++) {
                    LxDatas.add(lxInfoDao.loadAll().get(i).getLXMC());
                }
                setOption(LxDatas, lxTe, 1);
                break;
            case R.id.xcsj_lay:
                TimePickerView ksTimes = new TimePickerView.Builder(DieaseAddActivity.this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        xcsjTe.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date));
                    }
                }).setType(new boolean[]{true, true, true, true, true, true})
                        .build();
                ksTimes.setDate(Calendar.getInstance());
                ksTimes.show();
                break;
            case R.id.bhlx_lay:
                List<String> bhlxDatas = new ArrayList<>();
                bhlxDatas.clear();
                for (int i = 0; i < bhInfoDao.loadAll().size(); i++) {
                    bhlxDatas.add(bhInfoDao.loadAll().get(i).getCATEGORYCODE());
                }
                setOption(bhlxDatas, bhlxTe, 2);
                break;
            case R.id.bhmc_lay:
                if (ID == null) {
                    ToastUtils.showShort("请先选择病害类型");
                } else {
                    List<String> bhmcDatas = new ArrayList<>();
                    bhmcDatas.clear();
                    List<BhLxInfo> BhLxInfo = bhLxInfoDao.queryBuilder().where(BhLxInfoDao.Properties.ParentId.eq(ID)).list();
                    for (int i = 0; i < BhLxInfo.size(); i++) {
                        bhmcDatas.add(BhLxInfo.get(i).getBHLX());
                    }
                    setOption(bhmcDatas, bhmcTe, 3);
                }
                break;
            case R.id.disease_shang_txt:
                ShangSelect();
                break;
            case R.id.disease_xia_txt:
                XiaSelect();
                break;
            case R.id.disease_quan_txt:
                QuanSelect();
                break;
            case R.id.save_te:
                String SzhKm = szhKm.getText().toString();
                String SzhBm = szhBm.getText().toString();
                String TzhKm = tzhKm.getText().toString();
                String TzhBm = tzhBm.getText().toString();
                if (StringUtils.isEmpty(SzhKm)) {
                    ToastUtils.showShort("请输入桩号");
                    return;
                }
                if (StringUtils.isEmpty(SzhBm)) {
                    SzhBm = "0";
                }
                if (StringUtils.isEmpty(TzhKm)) {
                    ToastUtils.showShort("请输入桩号");
                    return;
                }
                if (StringUtils.isEmpty(TzhBm)) {
                    TzhBm = "0";
                }
                if (StringUtils.isEmpty(bhlxTe.getText().toString())) {
                    ToastUtils.showShort("您输入的病害类型为空，请重新选择");
                    return;
                }
                if (StringUtils.isEmpty(bhmcTe.getText().toString())) {
                    ToastUtils.showShort("您输入的病害名称为空，请重新选择");
                    return;
                }
                String fxStr = "";
                if (SelInt == 1) {
                    fxStr = diseaseShangTxt.getText().toString();
                } else if (SelInt == 2) {
                    fxStr = diseaseXiaTxt.getText().toString();
                } else if (SelInt == 3) {
                    fxStr = diseaseQuanTxt.getText().toString();
                }
                String imgStr = "";
                ArrayList<String> listImgUrl = dieaseAddGird.getListImgUrl();
                if (listImgUrl != null && listImgUrl.size() > 0) {
                    for (int k = 0; k < listImgUrl.size(); k++) {
                        if (k == 0) {
                            imgStr += listImgUrl.get(k);
                        } else {
                            imgStr += "," + listImgUrl.get(k);
                        }
                    }
                }
                DieaseInfo dieaseInfo = new DieaseInfo();
                dieaseInfo.setCXRY(xcryTe.getText().toString());
                dieaseInfo.setLXID(LXID);
                dieaseInfo.setLXMC(LXMC);
                dieaseInfo.setXCSJ(xcsjTe.getText().toString());
                dieaseInfo.setSDZH(SzhKm + "." + SzhBm);
                dieaseInfo.setTJZH(TzhKm + "." + TzhBm);
                dieaseInfo.setXSFX(fxStr);
                dieaseInfo.setBHLX(BHLXMC);
                dieaseInfo.setBHMCMC(BHMCMC);
                dieaseInfo.setBHMCID(BHMCID);
                dieaseInfo.setBHSL(bhslTe.getText().toString());
                dieaseInfo.setBZ(bzEt.getText().toString());
                dieaseInfo.setTPDZ(imgStr);
                dieaseInfo.setISDB("1");
                dieaseInfo.setBHID("");
                dieaseInfoDao.insertInTx(dieaseInfo);
                ToastUtils.showShort("添加成功");
                Intent intent = new Intent();
                setResult(2, intent);
                finish();
                break;
            case R.id.add_te:
                String SzhKm2 = szhKm.getText().toString();
                String SzhBm2 = szhBm.getText().toString();
                String TzhKm2 = tzhKm.getText().toString();
                String TzhBm2 = tzhBm.getText().toString();
                if (StringUtils.isEmpty(SzhKm2)) {
                    ToastUtils.showShort("请输入桩号");
                    return;
                }
                if (StringUtils.isEmpty(SzhBm2)) {
                    SzhBm2 = "0";
                }
                if (StringUtils.isEmpty(TzhKm2)) {
                    ToastUtils.showShort("请输入桩号");
                    return;
                }
                if (StringUtils.isEmpty(TzhBm2)) {
                    TzhBm2 = "0";
                }
                if (StringUtils.isEmpty(bhlxTe.getText().toString())) {
                    ToastUtils.showShort("您输入的病害类型为空，请重新选择");
                    return;
                }
                if (StringUtils.isEmpty(bhmcTe.getText().toString())) {
                    ToastUtils.showShort("您输入的病害名称为空，请重新选择");
                    return;
                }
                String fxStr2 = "";
                if (SelInt == 1) {
                    fxStr2 = diseaseShangTxt.getText().toString();
                } else if (SelInt == 2) {
                    fxStr2 = diseaseXiaTxt.getText().toString();
                } else if (SelInt == 3) {
                    fxStr2 = diseaseQuanTxt.getText().toString();
                }
                DieaseJson dieaseJson = new DieaseJson();
                dieaseJson.setGYDW(MyAppliCation.spUtils.getString("GydwId"));
                dieaseJson.setQDZH(SzhKm2 + "." + SzhBm2);
                dieaseJson.setDCSJ(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                dieaseJson.setDCR(MyAppliCation.spUtils.getString("OrgName"));
                dieaseJson.setWZFX(fxStr2);
                dieaseJson.setBHMC(BHMCID);
                dieaseJson.setTJQDZH(TzhKm2 + "." + TzhBm2);
                dieaseJson.setYGSL(bhslTe.getText().toString());
                dieaseJson.setLXCODE(LXID);
                dieaseJson.setSHBW(BHLXMC);
                dieaseJson.setBZ(bzEt.getText().toString());
                dieaseJson.setCREATOR(MyAppliCation.spUtils.getString("OrgName"));
                String imgStr2 = "";
                ArrayList<String> listImgUrl2 = dieaseAddGird.getListImgUrl();
                if (listImgUrl2 != null && listImgUrl2.size() > 0) {
                    for (int k = 0; k < listImgUrl2.size(); k++) {
                        if (k == 0) {
                            imgStr2 += listImgUrl2.get(k);
                        } else {
                            imgStr2 += "," + listImgUrl2.get(k);
                        }
                    }
                }
                if (!StringUtils.isSpace(imgStr2)) {
                    String[] strArr = imgStr2.split(",");
                    if (strArr != null && strArr.length > 0) {
                        ArrayList<DieaseJson.PICBean> listPic = new ArrayList<>();
                        for (int i = 0; i < strArr.length; i++) {
                            DieaseJson.PICBean picInfo = new DieaseJson.PICBean();
                            String imgUrl = strArr[i];
                            String nameStr = imgUrl.substring(imgUrl.lastIndexOf("/") + 1, imgUrl.length());
                            String typeStr = imgUrl.substring(imgUrl.lastIndexOf(".") + 1, imgUrl.length());
                            picInfo.setPicFileName(nameStr);
                            picInfo.setPicFileType(typeStr);
                            String strBlob = MyUtils.bmpToBase64String(imgUrl);
                            picInfo.setPicDataBlob(strBlob);
                            listPic.add(picInfo);
                        }
                        dieaseJson.setPIC(listPic);
                    }
                }
                List<DieaseJson> sss = new ArrayList<>();
                sss.add(dieaseJson);
                String json = new Gson().toJson(sss);
                mPresenter.addLog(json, DieaseAddActivity.this);
                break;
        }
    }

    public void setOption(final List<String> datas, final TextView textview, final int type) {
        pickerView = new OptionsPickerView.Builder(DieaseAddActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                if (type == 1) {//路线
                    LXMC = lxInfoDao.loadAll().get(options1).getLXMC();
                    LXID = lxInfoDao.loadAll().get(options1).getLXID();
                } else if (type == 2) {
                    ID = bhInfoDao.loadAll().get(options1).getId();
                    BHLXMC = bhInfoDao.loadAll().get(options1).getCATEGORYCODE();
                    bhlxTe.setText("");
                } else if (type == 3) {
                    BHMCID = bhLxInfoDao.loadAll().get(options1).getBHLXID();
                    BHMCMC = bhLxInfoDao.loadAll().get(options1).getBHLX();
                }
                String tx = datas.get(options1);
                textview.setText(tx);
            }
        }).setLayoutRes(R.layout.progress_lay, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                TextView ivCancel = (TextView) v.findViewById(R.id.iv_cancel);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pickerView.returnData();
                        pickerView.dismiss();
                    }
                });
                ivCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pickerView.dismiss();
                    }
                });
            }
        }).build();
        pickerView.setPicker(datas);
        pickerView.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            final DieaseAddGird dieaseAddGird = mapAdapter.get(childViewPosition);
            final ArrayList<Drawable> listPicture = dieaseAddGird.getListPicture();
            final ArrayList<String> listImgUrl = dieaseAddGird.getListImgUrl();
            String imgPath = Matisse.obtainCropResult(data);
            listPicture.remove(listPicture.size() - 1);
            Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
            if (bitmap != null) {
                Drawable drawable = new BitmapDrawable(bitmap);
                listPicture.add(drawable);
                listImgUrl.add(imgPath);
                Drawable addPicture = getResources().getDrawable(R.drawable.img_add_pic);
                listPicture.add(addPicture);
                dieaseAddGird.notifyDataSetChanged();
            }
        }
    }

    private void ShangSelect() {
        if (SelInt != 1) {
            SelInt = 1;
            diseaseShangTxt.setTextColor(getResources().getColor(R.color.white));
            diseaseShangTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.up_but_shap));
            diseaseXiaTxt.setTextColor(getResources().getColor(R.color.theme_color));
            diseaseXiaTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.down_but_shap));
            diseaseQuanTxt.setTextColor(getResources().getColor(R.color.theme_color));
            diseaseQuanTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.down_but_shap));
        }
    }

    private void XiaSelect() {
        if (SelInt != 2) {
            SelInt = 2;
            diseaseShangTxt.setTextColor(getResources().getColor(R.color.theme_color));
            diseaseShangTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.down_but_shap));
            diseaseXiaTxt.setTextColor(getResources().getColor(R.color.white));
            diseaseXiaTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.up_but_shap));
            diseaseQuanTxt.setTextColor(getResources().getColor(R.color.theme_color));
            diseaseQuanTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.down_but_shap));
        }
    }

    private void QuanSelect() {
        if (SelInt != 3) {
            SelInt = 3;
            diseaseShangTxt.setTextColor(getResources().getColor(R.color.theme_color));
            diseaseShangTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.down_but_shap));
            diseaseXiaTxt.setTextColor(getResources().getColor(R.color.theme_color));
            diseaseXiaTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.down_but_shap));
            diseaseQuanTxt.setTextColor(getResources().getColor(R.color.white));
            diseaseQuanTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.up_but_shap));
        }
    }

    @Override
    public void addLogs(String data) {
        if (data.equals("1")) {
            ToastUtils.showShort("上传成功");
            Intent intent = new Intent();
            setResult(2, intent);
            finish();
        }
    }
}
